
package com.probiz.estoresa.product.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.common.model.product.Brand;
import com.probiz.estore.common.model.product.ProductType;
import com.probiz.estore.common.model.product.ProductTypeSkuOption;
import com.probiz.estore.common.model.product.SkuOption;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.model.BaseObject;
import com.probiz.estore.product.model.ProductTypeFullyModel;
import com.probiz.estore.product.service.BrandManager;
import com.probiz.estore.product.service.ProductTypeManager;
import com.probiz.estore.product.service.SkuOptionManager;
import com.probiz.estore.webapp.util.RequestUtil;

public class ProductTypeController extends
		GenericStoreAdminController<ProductType> {
	private ProductTypeManager	productTypeManager	= null;
	private SkuOptionManager	skuOptionManager	= null;
	private BrandManager		brandManager		= null;

	public void setProductTypeManager(ProductTypeManager inMgr) {
		this.productTypeManager = inMgr;
	}

	public void setSkuOptionManager(SkuOptionManager skuOptionManager) {
		this.skuOptionManager = skuOptionManager;
	}

	public void setBrandManager(BrandManager brandManager) {
		this.brandManager = brandManager;
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(ProductType entity) {
		return entity.getProductTypeName();
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.BaseController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = productTypeManager;
	}
	
	@Override
	protected Map<String,String> getSortMap(){
		Map<String,String> sortMap = new HashMap<String,String>();
		sortMap.put("1", "convert_gbk(productTypeName)");
		return sortMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#preSave(javax.servlet.http.HttpServletRequest,
	 *      java.lang.Object, org.springframework.validation.BindException)
	 */

	@Override
	protected void onShowForm(HttpServletRequest request, ModelAndView mv) {
		ProductType productType = (ProductType) mv.getModel()
				.get("productType");
		// 关联品牌开始
		List<Brand> relatedBrands = productTypeManager
				.getRelatedBrand(productType.getProductTypeId());
		mv.addObject("relatedBrands", relatedBrands);

		List<Brand> nonRelatedBrands = brandManager.listAll();
		Iterator<Brand> biterator = nonRelatedBrands.iterator();
		while (biterator.hasNext()) {
			Brand brand = biterator.next();
			if (relatedBrands.contains(brand)) {
				biterator.remove();
			}
		}
		mv.addObject("nonRelatedBrands", nonRelatedBrands);
		// 关联品牌结束
		// 关联规格开始
		List<SkuOption> relatedSkuOptions = productTypeManager
				.getRelatedSkuOption(productType.getProductTypeId());
		mv.addObject("relatedSkuOptions", relatedSkuOptions);

		List<SkuOption> nonRelatedSkuOptions = skuOptionManager.listAll();
		Iterator<SkuOption> siterator = nonRelatedSkuOptions.iterator();
		while (siterator.hasNext()) {
			SkuOption skuOption = siterator.next();
			if (relatedSkuOptions.contains(skuOption)) {
				siterator.remove();
			}
		}
		mv.addObject("nonRelatedSkuOptions", nonRelatedSkuOptions);

		List<Integer> isQuickSearchs = new ArrayList<Integer>();
		for (ProductTypeSkuOption productTypeSkuOption : productType
				.getProductTypeSkuOptions()) {
			isQuickSearchs.add(productTypeSkuOption.getIsQuickSearch());
		}
		mv.addObject("isQuickSearchs", isQuickSearchs.toArray(new Integer[0]));

		// 关联规格结束

	}

	public ModelAndView attributeDefine(HttpServletRequest request,
			HttpServletResponse response) {

		ModelAndView mv = new ModelAndView(
				"product/productTypeFormAttributeDefine");
		mv.addObject("attributeId", RequestUtil.getParameterNullSafe(request,
				"attributeId"));
		return mv;
	}

	@Override
	protected void preSave(HttpServletRequest request, ProductType entity, BindException errors) {
		if (entity.getProductTypeId()==null) {
			boolean isDuplicate = productTypeManager.getIsProductTypeExist(entity.getProductTypeName());
			if (isDuplicate) {
				//检查品牌是否重复
				Object[] params = { entity.getProductTypeName() };
				errors.rejectValue("productTypeName", "productType.productTypeName.isExist", "the productTypeName has exist !");
			}
		} else {
			//检查修改后的品牌是否已经存在
			if (productTypeManager.getIsProductTypeNameUseByOthers(entity.getProductTypeName(), entity.getProductTypeId())) {
				errors.rejectValue("productTypeName", "productType.productTypeName.isExist", "the productTypeName has exist !");
			}
		}

	}

	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		ProductType entity = formBackingObject(request);

		BindException errors = null;
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			preSave(request, entity, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				Map<String, Object> saveData = productTypeManager
						.saveFully(getProductTypeFullyModel(request, entity,
								data));
				data.putAll(saveData); // 这里页面返回由于不是用JSON返回，所以回传的id值可以不处理。
				postSave(request, entity);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}

		ModelAndView mav;
		if (errors.hasErrors()) {
			mav = showForm(request, errors);
		} else if (successView != null) {
			mav = getModelAndView(successView, errors.getModel());
		} else {
			mav = getRedirectToActionView("edit", ((BaseObject) entity).getId()
					.toString());
		}
		return mav;
	}

	/**
	 * 删除一条记录。并在应用级出错的时候显示出错信息。
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 取得Form对应的Model。因为要先保存其名称，否则可能会连I18N数据也已经删除了；另外可以用于出错的时候恢复显示Form页面
		ProductType entity = formBackingObject(request);
		try {
			// 删除并设置信息
			String entityId = request.getParameter(entityIdName);
			if (!StringUtils.isEmpty(entityId)) {
				// 先构造提示信息，否则信息对应的记录可能也会被删除。
				String entityName = getEntityName(entity);
				entity = productTypeManager.getById(new Integer(entityId));
				short deleteStatus = productTypeManager.deleteFully(new Integer(entityId));
				String message = "";
				if(productTypeManager.DELETE_STATUS_TRUE.equals(deleteStatus)){
					message = getMessage("common.deleted", new Object[] {
							getEntityTypeMessage(), entityName });
					saveMessage(request, message);
					
				}else{
					message = getMessage("productType.delete.false", new Object[] {
							getEntityTypeMessage(), entityName });
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("productType", entity);
					saveErrorMessage(request, message);
					return getModelAndView(formView, map);
				}
				
				
			} else {
				saveMessage(request, getMessage("errors.invalid.delete.id",
						new Object[] { entityId }));
			}
		} catch (ApplicationException e) {
			
			// 为了出错的时候可以恢复表单显示，构造errors。无须作表单绑定和验证
			ServletRequestDataBinder binder = this.getDefaultBinder(request,entity);
			BindException errors = new BindException(binder.getBindingResult());
			handleApplicationException(errors, e);
			
			return showForm(request, errors);
		}

		return getModelAndView(cancelFormView, null);
	}

	
	public ModelAndView multiDelete(HttpServletRequest request,
			HttpServletResponse response) {
		// 取得要删除的记录的id的列表。注意：选择框的id要是"multiIds"。
		String[] ids = request.getParameterValues("multiIds");
		if (ids != null && ids.length > 0) {
			for(String entityId :ids){
				ProductType entity = productTypeManager.getById(new Integer(entityId));
				short deleteStatus = productTypeManager.deleteFully(new Integer(entityId));
				String message = "";
				if(productTypeManager.DELETE_STATUS_TRUE.equals(deleteStatus)){
					message = getMessage("common.deleted", new Object[] {getEntityTypeMessage(), entity.getProductTypeName() });
					saveMessage(request, message);
					
				}else{
					message = getMessage("productType.delete.false", new Object[] {getEntityTypeMessage(), entity.getProductTypeName() });
					saveErrorMessage(request, message);
				}
			}
		}
		return getRedirectToActionView("search");
	}
	
	// 构造商品类型模型，方便保存
	private ProductTypeFullyModel getProductTypeFullyModel(
			HttpServletRequest request, ProductType productType,
			Map<String, Object> data) {
		ProductTypeFullyModel model = new ProductTypeFullyModel();
		model.setProductType(productType);

		// ---------- start:绑定关联品牌值--------------

		String[] relatedBrandIds = RequestUtil.getParameterValuesNullSafe(
				request, "relatedBrandIds");
		model.setRelatedBrandIds(relatedBrandIds);
		// --------- end:绑定关联品牌值值----------------

		// ---------- start:绑定关联品牌值--------------

		String[] relatedSkuOptionIds = RequestUtil.getParameterValuesNullSafe(
				request, "relatedSkuOptionIds");
		String[] skuOptionIsQuickSearchs = RequestUtil
				.getParameterValuesNullSafe(request, "isQuickSearch");
		model.setRelatedSkuOptionIds(relatedSkuOptionIds);
		model.setSkuOptionIsQuickSearchs(skuOptionIsQuickSearchs);
		// --------- end:绑定关联品牌值值----------------

		// --------- start: 绑定属性组----------------
		String[] groupIds = (String[]) ArrayUtils.clone(RequestUtil
				.getParameterValuesNullSafe(request, "groupIds"));
		String[] groupNames = RequestUtil.getParameterValuesNullSafe(request,
				"groupNames");
		String[] groupSortOrders = RequestUtil.getParameterValuesNullSafe(
				request, "groupSortOrders");

		// 传入返回map
		data.put("oldGroupIds", groupIds);
		model.setOldGroupIds(groupIds);
		String[] newGroupIds = (String[]) ArrayUtils.clone(groupIds);// 这里复制是为了可以在不改变request中的数据
		for (int i = 0; i < newGroupIds.length; i++) {
			if (newGroupIds[i].contains("new")) {
				// case:属性组是新增的
				newGroupIds[i] = "";
			} else {
				// case:属性组已存在
				newGroupIds[i] = newGroupIds[i].substring(newGroupIds[i]
						.indexOf("_") + 1);
			}
		}
		model.setGroupIds(newGroupIds);
		model.setGroupNames(groupNames);
		model.setGroupSortOrders(groupSortOrders);
		// --------- end: 绑定属性组----------------

		// --------- start: 绑定attrItem----------------
		String[] attrItemIds = (String[]) ArrayUtils.clone(RequestUtil
				.getParameterValuesNullSafe(request, "aiIds"));
		String[] attrItemGroupIds = RequestUtil.getParameterValuesNullSafe(
				request, "aiGroupIds");
		String[] attrItemAttributeIds = RequestUtil.getParameterValuesNullSafe(
				request, "aiAttributeIds");
		String[] attrItemSortOrders = RequestUtil.getParameterValuesNullSafe(
				request, "aiSortOrders");
		String[] attrItemIsQuickSearchs = RequestUtil
				.getParameterValuesNullSafe(request, "aiIsQuickSearchs");
		String[] attrItemShowStyles = RequestUtil.getParameterValuesNullSafe(
				request, "aiShowStyles");
		String[] attrItemSearchValues = RequestUtil.getParameterValuesNullSafe(
				request, "aiSearchValues");

		// 传入返回map
		data.put("oldAttrItemIds", attrItemIds);
		data.put("oldAttrItemGroupIds", attrItemGroupIds);
		model.setOldAttrItemIds(attrItemIds);
		model.setOldAttrItemGroupIds(attrItemGroupIds);
		String[] newAttrItemIds = (String[]) ArrayUtils.clone(attrItemIds);// 这里复制是为了可以在不改变request中的数据
		for (int i = 0; i < newAttrItemIds.length; i++) {
			if (newAttrItemIds[i].contains("new")) {
				// case:sku是新增的
				newAttrItemIds[i] = "";
			} else {
				// case:sku已存在
				newAttrItemIds[i] = newAttrItemIds[i]
						.substring(newAttrItemIds[i].indexOf("_") + 1);
			}
		}
		model.setAttrItemIds(newAttrItemIds);
		model.setAttrItemAttributeIds(attrItemAttributeIds);
		model.setAttrItemSortOrders(attrItemSortOrders);
		model.setAttrItemIsQuickSearchs(attrItemIsQuickSearchs);
		model.setAttrItemShowStyles(attrItemShowStyles);
		model.setAttrItemSearchValues(attrItemSearchValues);
		// --------- end: 绑定attrItem----------------
		// --------- start: 绑定delete attributeIds----------------
		String deleteAttributeIdString = RequestUtil.getParameterNullSafe(
				request, "deleteAttributeIdString");
		if (!StringUtils.isEmpty(deleteAttributeIdString)) {
			String[] deleteAttributeIds = deleteAttributeIdString.substring(0,
					deleteAttributeIdString.length() - 1).split(",");
			model.setDeleteAttributeIds(deleteAttributeIds);
		}

		// --------- end: 绑定delete attributeIds----------------
		return model;
	}
	/**
	 * 移除规格关联检查
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView removeSkuOptionCheck(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		Long size = skuOptionManager.getSizeOfProductSkuOptionValueByProductTypeAndSkuOption(RequestUtil.getInteger(request, "productTypeId"),RequestUtil.getInteger(request, "skuOptionId"));
		if(size > 0){
			data.put("result", "result=0");
		}else{
			data.put("result", "result=1");
		}
		return getModelAndAjaxJsonView(data);
	}

}
